"""
@Author：十
@Time：2024/10/10 16:51
@FileName：detect.py
@Description：点击“数据管理”按钮之后跳出来的指定检测位置的窗口
"""
import sqlite3
import sys

from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from UI.detect import Ui_Form


class DeleteWindow(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(DeleteWindow, self).__init__()

        self.parent = parent

        self.setupUi(self)

        self.pushButton.clicked.connect(self.Confirm)

        self.InterfaceInit()

    def InterfaceInit(self):
        # comboBox可编辑
        self.comboBox.setEditable(True)
        self.comboBox_2.setEditable(True)
        self.comboBox.setPlaceholderText(" ")
        self.comboBox_2.setPlaceholderText(" ")

        conn = sqlite3.connect('./DB/digitization.db')
        cursor = conn.cursor()

        cursor.execute("SELECT station, pos FROM detect_info")
        rows = cursor.fetchall()

        stations = set()
        positions = set()
        # 将结果添加到 ComboBox
        for row in rows:
            station, pos = row
            stations.add(station)
            positions.add(pos)

        conn.close()

        self.comboBox.addItems(sorted(stations))
        self.comboBox_2.addItems(sorted(positions))

    def Confirm(self):
        station = self.comboBox.currentText()
        pos = self.comboBox_2.currentText()

        if not station or not pos:
            QMessageBox.warning(self, "输入错误", "请填写完整信息")
            return

        try:
            conn = sqlite3.connect('./DB/digitization.db')
            cursor = conn.cursor()

            cursor.execute("INSERT OR IGNORE INTO detect_info (station, pos) VALUES (?, ?)", (station, pos))
            conn.commit()

        except sqlite3.Error as e:
            QMessageBox.critical(self, "数据库错误", f"数据保存失败：{e}")

        finally:
            conn.close()
            try:
                self.parent.Signal_Submit_Data.emit(station, pos)
            except Exception as e:
                print('数据提交错误：', e)
            self.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = DeleteWindow()
    mainWindow.show()
    sys.exit(app.exec_())
